package com.cdty.chess.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import com.cdty.chess.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import com.cdty.chess.util.FileUtils;
import com.cdty.chess.util.FileUtils.CosFileList;
import com.cdty.chess.util.FileUtils.FileUploadRequest;

import lombok.RequiredArgsConstructor;

/**
 * 文件服务实现类
 */
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {
    
    private final FileUtils fileUtils;
    
    @Override
    public List<String> uploadFiles(List<MultipartFile> files) {
        Assert.notEmpty(files, "上传文件列表不能为空");
        
        var uploadRequests = files.stream()
                .map(file -> {
                    try {
                        return new FileUploadRequest(
                            file.getInputStream(),
                            file.getOriginalFilename(),
                            file.getContentType(),
                            file.getSize()
                        );
                    } catch (IOException e) {
                        e.getStackTrace();
                        return null;
                        //throw new ApiErrorException("文件读取失败: " + file.getOriginalFilename(), e);
                    }
                })
                .collect(Collectors.toList());
        
        return fileUtils.uploadFiles(uploadRequests);
    }
    
    @Override
    public void deleteFiles(List<String> fileUrls) {
        Assert.notEmpty(fileUrls, "删除文件列表不能为空");
        fileUtils.deleteFiles(fileUrls);
    }
    
    @Override
    public CosFileList listFiles(String directory) {
        return fileUtils.listFiles(directory);
    }
    
    @Override
    public void createDirectory(String directory) {
        Assert.hasText(directory, "目录路径不能为空");
        fileUtils.createDirectory(directory);
    }
}